<template>
  <!-- https://img95.699pic.com/photo/40007/8824.jpg_wh300.jpg!/fh/210 -->
  <div v-if="schoolConfig" class="login-container" :style="{'backgroundImage': 'url(' + require('../../assets/login_bg_1.jpg') + ')'}">
    <div class="headline flex_between">
      <div class="flex_center_align">
        <el-image style="height: 70px" fit="scale-down" :src="require('../../assets/gp_logo.png')" />
        <div style="color: rgb(64, 158, 255);font-size: 38px;margin-left: 15px">{{ schoolConfig.title }}</div>
      </div>
      <!-- <el-image style="height: 70px" fit="scale-down" :src="require('../../assets/logo.png')" alt="" /> -->
    </div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="formRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <div class="title">
          {{ '管理员登录' }}
        </div>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入账号"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
          @blur="getCaptcha"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>
      <!-- 滑块 -->
      <div v-if="schoolConfig.login_captcha" class="check" @mousedown="onMouseDown" @mouseup="onMouseUp" @mousemove="onMouseMove">
        <div
          ref="sliderCon"
          class="slider-con "
          style="z-index: 9999999;"
          :class="{'err-anim':showError, 'verify-success': showSuccess}"
          :style="{
            'background': showSuccess ? '#D2F4EF' : showError ? '#FCE1E1' : '#D0E8FF',
            'border': showSuccess ? '2px solid #52CCBA' : showError ? '2px solid #F57A7A' : '2px solid #409EFF'
          }"
        >
          <div id="slider" ref="slider" class="slider" :class="{sliding}" :style="{'--move': `${slidMove}px`}" />
          <div v-if="(sliding && !checking) || slidMove > 1" style="width: 330px;position: absolute;bottom: 60px;background: #FFFFFF;border-radius: 8px;padding: 0 12px 12px 12px;">
            <div style="padding: 10px;position: absolute;right: 0;cursor:pointer" @click="resetSlider()">
              <div style="background: red;color: #FFFFFF;width: 16px;height: 16px;border-radius: 50px;text-align: center;line-height: 16px;">×</div>
            </div>
            <p style="color: #409FFF;font-size: 18px;font-weight: bold;text-align: center;">拖动滑块,使图片角度为正</p>
            <div style="display: flex; flex-direction: row; justify-content: center;">
              <div v-loading="loadCaptchaPath" class="img-con">
                <img :src="captchaPath" :style="{transform: imgAngle}" @load="loadImg">
              </div>
            </div>
          </div>
          <div
            v-if="slidMove > 10"
            style="height: 38px;position: absolute;border: 1px solid #FFFFFF;border-radius: 50px;top: 0;margin: 1px"
            :style="{'width': `${slidMove + 30}px`, 'background': showSuccess ? '#52CCBA' : showError ? '#F57A7A' : '#409EFF'}"
          />
          <div
            v-if="!showSuccess && !showError"
            style="line-height: 40px;position: absolute;border-radius: 50px;top: 0;font-size: 16px;width: 100%;font-weight: bold;color: #429FFF;text-align: center;"
          >向右滑动登录</div>
        </div>
      </div>
      <el-button v-if="!schoolConfig.login_captcha" :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登 录</el-button>
    </el-form>
    <div style="opacity: 1;position: fixed;width: 100px;height: 100px;bottom: -100px;left: -100px;">
      <el-image lazy style="width: 100px; height: 100px" :src="captchaPath" fit="contain" />
    </div>
    <div v-if="(sliding && !checking) || slidMove > 1" style="position: fixed;background:rgba(0,0,0,0.5);width: 100%;height: 100%;z-index: 99" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { get, post } from '@/api/request'
import { setToken, setRefreshToken } from '@/utils/auth'
import store from '@/store'
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: '',
        captcha_token: ''
      },
      developmentApi: require('@/settings.js').developmentApi,
      formRules: this.$validateField['Login'],
      loading: false,
      passwordType: 'password',
      capsTooltip: false, // 没懂
      redirect: undefined,
      is_edit: undefined,
      uuid: '',
      captchaPath: '',
      // 滑块
      showError: false,
      showSuccess: false,
      checking: false,
      sliding: false,
      slidMove: 0,
      loadCaptchaPath: false
    }
  },
  computed: {
    ...mapGetters([
      'schoolConfig'
    ]),
    // 滑块
    angle() {
      const sliderConWidth = this.sliderConWidth ?? 0
      const sliderWidth = this.sliderWidth ?? 0
      const ratio = this.slidMove / (sliderConWidth - sliderWidth)
      return 360 * ratio
    },
    imgAngle() {
      return `rotate(${this.angle}deg)`
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
        if (route.query && route.query.is_edit) {
          this.is_edit = true
        }
      },
      immediate: true
    }
  },
  methods: {
    // 图片加载完成
    loadImg() {
      this.loadCaptchaPath = false
    },
    // 重置滑块
    resetSlider(move = 0) {
      this.sliding = false
      this.slidMove = move
      this.checking = false
      this.showSuccess = false
      this.showError = false
    },
    // 鼠标在元素上点击后触发
    onMouseDown(event) {
      if (event.target.id !== 'slider') return false
      // if (this.checking) return
      // 设置状态为滑动中
      this.sliding = true
      this.checking = false
      // 下面三个变量不需要监听变化，因此不放到 data 中
      this.sliderLeft = event.clientX // 记录鼠标按下时的x位置
      this.sliderConWidth = this.$refs.sliderCon.clientWidth // 记录滑槽的宽度
      this.sliderWidth = this.$refs.slider.clientWidth // 记录滑块的宽度
    },
    // 鼠标按键被松开时执行
    onMouseUp(event) {
      if (this.sliding && this.checking === false) {
        this.checking = true
        this.sliding = false
        this.sliderChange(Math.round(this.angle))
      }
    },
    // 在鼠标指针移到指定的元素后执行Javascript代码
    onMouseMove(event) {
      if (!this.loginForm.username) return false
      if (this.sliding && this.checking === false && this.loadCaptchaPath === false) {
        // 滑块向右的平移距离等于鼠标移动事件的X坐标减去鼠标按下时的初始坐标。
        let m = event.clientX - this.sliderLeft
        if (m < 0) {
          // 如果m小于0表示用户鼠标向左移动超出了初始位置，也就是0
          // 所以直接等于 0，以防止越界
          m = 0
        } else if (m > this.sliderConWidth - this.sliderWidth) {
          // 滑块向右移动的最大距离是滑槽的宽度减去滑块的宽度。
          // 因为css的 translateX 函数是以元素的左上角坐标计算的
          // 所以要减去滑块的宽度，这样滑块在最右边时，才不会左上角和滑槽右上角重合。
          m = this.sliderConWidth - this.sliderWidth
        }
        this.slidMove = m
      }
    },
    async sliderChange(e) {
      if (!e || !this.loginForm.username) return false
      // 请求接口验证旋转角度
      await post(`/api/captcha/${this.uuid}`, { username: this.loginForm.username, value: e }).then(response => {
        if (response.code === 0) {
          this.showSuccess = true
          Object.assign(this.loginForm, { captcha_token: response.data.captcha_token })
          this.handleLogin()
        } else {
          this.showError = true
          // 验证失败
          this.getCaptcha()
        }
      })
    },
    async getCaptcha(e) {
      if (this.loginForm.username === e?.target.value && this.captchaPath) return false
      if (!this.loginForm.username) return false
      this.loadCaptchaPath = true
      this.uuid = this.$uuid()
      await get(`/api/captcha/${this.uuid}`, { username: this.loginForm.username }).then(response => {
        if (response.code === 0) {
          this.captchaPath = response.data.image
          this.loadCaptchaPath = false
          if (!e) this.resetSlider(2)
        }
      })
    },
    checkCapslock(e) {
      // console.log('密码验证', e)
      // const { key } = e
      // this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    async handleLogin() {
      // if (process.env.NODE_ENV === 'development') { // 本地登录时获取密码
      //   const sunEvn = require('@/sun-env')
      //   const setting = require('@/settings')
      //   this.$set(this.loginForm, 'username', 'admin')
      //   this.$set(this.loginForm, 'password', sunEvn[setting.developmentApi])
      // }
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          post(`auth/login`, this.loginForm).then(response => {
            if (response.code === 0) {
              store.dispatch('user/toggleSetToken', response.data.token_type + ' ' + response.data.access_token)
              setToken(response.data.token_type + ' ' + response.data.access_token)
              store.dispatch('user/toggleRefreshToken', response.data.refresh_token)
              setRefreshToken(response.data.refresh_token)
              const _that = this
              setTimeout(() => {
                _that.$router.push({ path: _that.redirect || '/' })
              }, 200)
            } else {
              this.resetSlider(0)
            }
            this.loading = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.login-container {
  width: 100%;
		background-attachment: fixed;
		background-position: center;
		background-size: cover;
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      height: 47px;
    }
  }
}
.el-slider__bar {
  height:  30px;
  border-radius: 50px;
}
.el-slider__runway {
  height: 30px;
  border-radius: 50px;
}
.el-slider__button {
  width: 30px;
  height: 30px;
  border-radius: 50px;
  background: #409EFF;
  border: 2px solid #FFFFFF;
}
.el-slider__button-wrapper {
  top: -3px;
}
</style>

<style lang="scss" scoped>
.login-container ::v-deep {
    .el-form-item{
      border: 1px solid #bfcbd9;
      background-color: #FFFFFF !important;
    }
  }
.login-container {
  display: flex;
  flex-direction: row;
  align-items:center;
  min-height: 100%;
  width: 100%;
  overflow: hidden;

  .headline {
    position: fixed;
    top: 0;
    padding: 0 10%;
    background-color: rgba(255,255,255,0.9);
    box-shadow: 0 1px 15px rgb(0 0 0 / 30%);
    width: 100%;
    height: 100px;
  }

  .login-form {
    width: calc(420px - 20px);
    max-width: calc(100% - 20%);
    margin: 0 auto;
    // overflow: hidden;
    position: absolute;
    right: 10%;
    background: rgba(255, 255, 255, 0.9);
    padding: 35px;
    border-radius: 5px;
  }
  .svg-container {
    padding: 0px 5px 0px 15px;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      margin: 0px auto 40px auto;
      text-align: center;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
/** 滑块 */
.check {
  --slider-size: 40px;
}
.check .img-con {
  position: relative;
  overflow: hidden;
  width: 250px;
  height: 250px;
  border-radius: 50%;
}
.check .img-con img {
  width: 100%;
  height: 100%;
  user-select: none;
}

.check .slider-con {
  width: 100%;
  height: var(--slider-size) + 4px;
  border-radius: 50px;
  position: relative;
}

// 默认状态
.slider-con .slider {
  background-image: url();
  background-repeat: no-repeat;
  background-size: 100%;
  width: var(--slider-size);
  height: var(--slider-size);
  border-radius: 50%;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  cursor: move;
  --move: 0px;
  transform: translateX(var(--move));
  z-index: 99;
  position: inherit;
}

// 按下状态
.slider-con .slider.sliding {
  background-image: url();
  background-repeat: no-repeat;
  background-size: 100%;
  position: inherit;
}

// 验证失败状态
.slider-con.err-anim .slider {
  background-image: url();
  background-repeat: no-repeat;
  background-size: 100%;
  position: inherit;
}
// 验证成功状态
.slider-con.verify-success .slider {
  background-image: url();
  background-repeat: no-repeat;
  background-size: 100%;
  position: inherit;
}

@keyframes jitter {
  20% {
    transform: translateX(-5px);
  }
  40% {
    transform: translateX(10px);
  }
  60% {
    transform: translateX(-5px);
  }
  80% {
    transform: translateX(10px);
  }
  100% {
    transform: translateX(0);
  }
}

// 失败抖动
.slider-con.err-anim {
  animation: jitter 0.5s;
}

</style>
